let express = require("express");

let Router = express.Router(); //获取Router对象用于开启路由 Router==app，比app对象多了路由管理功能
let query = require("../../db/mysql");
let { create, verify } = require("./token");
/*
    用户管理相关接口：
        * 验证用户名是否存在 get
        * 注册 post
        * 登录 get 7天免登录
        * 查询列表 get
        * 删除用户 delete
        * 修改密码 put
*/

//验证用户名是否存在 get
Router.get("/checkname", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    let { name } = req.query;
    // console.log(name, 888);
    let str = `SELECT * FROM user_inf WHERE name='${name}'`;
    let p = await query(str); //[{}]
    // console.log(p);

    if (p.length) {
      //不为零:已存在,不能注册
      data = {
        code: 3000,
        flag: false,
        message: "账号已存在，请换一个用户名",
      };
    } else {
      //不存在，可以注册
      data = {
        code: 2000,
        flag: true,
        message: "允许注册",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  res.send(data);
});

//注册 post
Router.post("/reg", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    let { name, password } = req.body;
    console.log(name, password, 888);
    let str = `INSERT INTO user_inf(name,psw) VALUES('${name}','${password}')`;
    let p = await query(str); //[{}]
    console.log(p);

    if (p.affectedRows) {
      //不为零:注册成功
      data = {
        code: 2000,
        flag: true,
        message: "注册成功",
      };
    } else {
      //注册失败
      data = {
        code: 3000,
        flag: false,
        message: "注册失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  res.send(data);
  //   res.send("666");
});

//登录 get 7天免登录
Router.get("/login", async (req, res) => {
  //   console.log("测试");
  let data = {};
  try {
    let { name, password } = req.query;
    // console.log(name, 888);
    let str = `SELECT * FROM user_inf WHERE name='${name}' AND psw='${password}'`;
    let p = await query(str); //[{}]
    // console.log(p);

    if (p.length) {
      //不为零:可以登录
      data = {
        code: 2000,
        flag: true,
        message: "登录成功",
        token: create(password),
      };
    } else {
      //登录失败
      data = {
        code: 3000,
        flag: false,
        message: "登录失败",
      };
    }
  } catch (err) {
    console.log(err);
    data = {
      code: 5000,
      flag: false,
      message: "服务器异常",
    };
  }

  res.send(data);
});

//校验token
Router.get("/verify", (req, res) => {
  //   console.log("测试");
  let data = {};

  let { token } = req.query;
  // console.log(name, 888);
  let result = verify(token);
  if (result) {
    //校验通过
    data = {
      code: 2000,
      flag: true,
      message: "校验通过",
    };
  } else {
    //校验失败
    data = {
      code: 3000,
      flag: false,
      message: "校验失败",
    };
  }

  res.send(data);
});

module.exports = Router;
